﻿using System.Collections;
using System.Collections.Generic;
using BearUtil.Hidden;
using Sirenix.OdinInspector;
using UnityEngine;
using XNodeEditor;

namespace BearUtil
{
    // Dialog Graph 自定义设置
    [CustomNodeGraphEditor(typeof(DialogGraph))]
    public class DialogGraphWindow : NodeGraphEditor
    {
        private DialogGraph graph;
        

        public override void OnGUI()
        {
            GUILayout.BeginHorizontal();
            /// back to last
            if (GUILayout.Button("返回"))
            {
                var dg = target as DialogGraph;
                // back to the story graph
                if (dg.owner == null)
                {
                    Debug.LogWarning("组件节点丢失");
                    return;
                }
                NodeEditorWindow.Open(dg.owner.graph);
            }

            GUI.color = Color.yellow;
            if (GUILayout.Button("刷新节点排序"))
            {
                if (graph == null)
                    return;

                graph.UpdateData();
            }


            GUI.color = Color.green;
            if (GUILayout.Button("导出 Excel"))
            {
                if (graph == null)
                    return;

                var sg = graph.owner.graph as StoryGraph;
                graph.OutputData(sg.GetOutputFolder());
            }
            

            GUILayout.EndHorizontal();
            
            base.OnGUI();
            
            if (window && graph.LastFocusPosition != window.panOffset)
            {
                // Debug.Log("Test ------");
                graph.LastFocusPosition = window.panOffset;
            }
        }

        public override void OnOpen()
        {
            base.OnOpen();
            graph = target as DialogGraph;
            
            var pos = graph.LastFocusPosition;
            window.panOffset = pos;
            window.titleContent = new GUIContent(graph.name);
            graph.UpdateData();
        }
        
        public override void OnWindowFocus()
        {
            base.OnWindowFocus();
            Debug.Log("OnFocus");
        }

        public void InitNode()
        {
            // 隐藏 start node 
            // add start node and end node in graph
            var start = graph.nodes.Find(node =>
            {
                return node.GetType() == typeof(StartNode);
            });

            if (start == null)
                CreateNode(typeof(StartNode), Vector2.zero);

            // add end node
            var end = graph.nodes.Find(node =>
            {
                return node.GetType() == typeof(EndNode);
            });

            if (end == null)
                CreateNode(typeof(EndNode), Vector2.zero);
        }
    }   
}
